package nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName ChannelDemo
 * @Description TODO
 * @Author lee ji liang
 * @DateTime 2021/8/26 10:57
 * @Version 1.0
 */
public class ChannelDemo {
    public static void main(String[] args) throws IOException {
        String filePath = "/xxx.txt";

        //文件输入流
        final FileInputStream fileInputStream = new FileInputStream(filePath);
        //获取输入通道
        final FileChannel inputChannel = fileInputStream.getChannel();

        // 文件输出流
        final FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        // 获取输出通道
        final FileChannel outputChannel = fileOutputStream.getChannel();

        // 随便访问文件对象
        var rw = new RandomAccessFile(filePath, "rw");
        // 文件流通道, 可读可写
        var channel = rw.getChannel();
        // 创建一个byteBuffer
        var buffer = ByteBuffer.allocate(1000);
        var read = channel.read(buffer);
        while (channel.read(buffer) != -1) {
            System.out.println(buffer.get());
        }

        // buffer翻转到读模式.
        buffer.flip();
        int outLength = -1;
        while ((outLength = channel.write(buffer)) != -1) {
            System.out.println(outLength);
        }
    }
}
